<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/9/12
 * Time: 下午3:19
 */

namespace Admin\Ims\Controllers;


use Admin\Models\ims\XHImsProdType;
use Admin\Models\ims\XHImsProduct;
use Helpers\Assets;
use Helpers\Cache;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\User;
use Helpers\UserPower;

class ProductController extends ControllerBase
{

    public function indexAction(){
        echo 'product';
    }

    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)->setJsonContent(['error' => 'Page Not Found']);
    }

    public function extraPower($tag){
        if(User::isAdmin()){
            return true;
        }
        $deps = User::getExtraPower('dep',$tag);
        $userIds = Hrm::getUserByDepId($deps);
        $newArr = [];
        foreach ($userIds as $ids){
            $newArr =array_merge($newArr,$ids);
        }
        $newArr = array_values(array_filter($newArr));

        return $newArr;
    }


    /**
     * 商品列表
     *
     * created by dale 2017/9/12
     */
    public function productListAction(){
        UserPower::checkUserPower('Ims_ProdList') or die('缺少权限');
        Assets::easyUI();
        Assets::importJs('js/product/productList.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/myTool.js');
        $this->view->pick('product/productList');

        Template::exists('typeList', 'list') or die(Main::showMessageModal('typeList配置文件不存在，请先创建！', 109106002));
        Template::exists('prodList', 'list') or die(Main::showMessageModal('prodList配置文件不存在，请先创建！', 109106002));
        $typeListButton = [];
        if(UserPower::checkUserPower('Ims_ProdList_Add')){
            $typeListButton[] = array('plain' => 'true', 'id' => 'bt_type_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if(UserPower::checkUserPower('Ims_ProdList_Del')){
            $typeListButton[] = array('plain' => 'true', 'id' => 'bt_type_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        
        $prodListButton = [];
        if(UserPower::checkUserPower('Ims_ProdList_Add')){
            $prodListButton[] = array('plain' => 'true', 'id' => 'bt_prod_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if(UserPower::checkUserPower('Ims_ProdList_Del')){
            $prodListButton[] = array('plain' => 'true', 'id' => 'bt_prod_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $this->view->setVars(array(
            'typeList' => Template::createList('typeList', 'typeList', [
//                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($typeListButton),
            ]),
            'prodList' => Template::createList('prodList', 'prodList', [
//                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($prodListButton),
            ]),
        ));
    }

    /**
     * 保存类型
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/9/12
     */
    public function saveTypeAction(){
        $id=$this->request->getPost('iTypeId','string') ;
        if($id){
            UserPower::checkUserPower('Ims_ProdList_Edit') or die('缺少权限');
            $obj = XHImsProdType::findFirst([
                'conditions'=>'bDelete=0 AND iTypeId=:iTypeId:',
                'bind'=>['iTypeId'=>$id],
            ]);
        }else{
            UserPower::checkUserPower('Ims_ProdList_Add') or die('缺少权限');
            $obj=new XHImsProdType();
        }
        $obj->assign($this->request->getPost());
        $check=$this->checkTypeName($this->request->getPost('sTypeName','string'),$id);
        if($check){
            return $this->sendErrorResponse(500,'该商品类型已存在,请不要重复创建');
        }
        if($obj->save()){
            if(Cache::exists('prodTypeEnum')){
                Cache::delete('prodTypeEnum');
            }
            if($id){
                return $this->sendSuccessResponse('编辑商品类型成功');
            }else{
                return $this->sendSuccessResponse('新增商品类型成功');
            }
        }else{
            if($id){
                return $this->sendSuccessResponse(500,'编辑商品类型失败');
            }else{
                return $this->sendErrorResponse(500,'新增商品类型失败');
            }
        }
    }


    /**
     * 获取类型分页
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/9/12
     */
    public function getTypeAction(){
        UserPower::checkUserPower('Ims_ProdList') or die('缺少权限');
        $condtionArr=[];
        $condtionArr['conditions']="bDelete = 0";
        $data= Main::runModelPage('Admin\Models\ims\XHImsProdType',$condtionArr,true);
        Main::runUserNameById($data['rows'],['iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'$iLastModifyUserId'],true);
        return $this->sendJsonResponse($data);
    }

    /**
     * 获取商品分页
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/9/12
     */
    public function getProductAction(){
        UserPower::checkUserPower('Ims_ProdList') or die('缺少权限');
        $iTypeId=$this->request->getPost('iTypeId','string');
        $condtionArr=[];
        $condtionArr['conditions']="bDelete = 0";
        $condtionArr['bind']=[];
        if($iTypeId){
            $condtionArr['conditions'].=" AND iTypeId=:iTypeId: ";
            $condtionArr['bind']=array_merge($condtionArr['bind'],array('iTypeId'=>$iTypeId));
        }
        if(!User::isAdmin()){
            $nowUserId = Main::getLoginUserInfo('userId');
            if(User::getExtraPower('dep','prod',$nowUserId,true)){ //有额外权限
                $userIds = $this->extraPower('prod');
                $condtionArr['conditions'] .= " AND ( iCreateUserId  in ({ids:array}) OR iCreateUserId = :iCreateUserId: ) ";
                $condtionArr['bind']         =array_merge($condtionArr['bind'],['ids'=>$userIds,'iCreateUserId' => $nowUserId]);
            }else{
                $condtionArr['conditions'] .= " AND  iCreateUserId = :iCreateUserId: ";
                $condtionArr['bind']         =array_merge($condtionArr['bind'],['iCreateUserId' => $nowUserId]);
            }
        }
        $data= Main::runModelPage('Admin\Models\ims\XHImsProduct',$condtionArr,true);
        Main::runUserNameById($data['rows'],['iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'$iLastModifyUserId'],true);
        return $this->sendJsonResponse($data);
    }


    /**
     * 检查类型名称是否存在
     * @param $name
     * @param null $id
     * @return bool
     *
     */
    public function checkTypeName($name,$id=null){
        if($id){
            $type=XHImsProdType::findFirst([
                'conditions'=>'bDelete=0 AND sTypeName=:sTypeName: AND iTypeId!=:iTypeId:',
                'bind'=>['sTypeName'=>$name,'iTypeId'=>$id]
            ]);
        }else{
            $type=XHImsProdType::findFirst([
                'conditions'=>'bDelete=0 AND sTypeName=:sTypeName:',
                'bind'=>['sTypeName'=>$name]
            ]);
        }
        if($type){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 删除类型
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/9/12
     */
    public function delTypeAction(){
        UserPower::checkUserPower('Ims_ProdList_Del') or die('缺少权限');
        $ids = $this->request->getPost('ids','string') or die('缺少参数');
        $ids = explode(',',$ids);
        if(Main::getLoginUserInfo('logonName') == 'admin'){
            $types=XHImsProdType::find([
                'conditions'=>'bDelete=0 AND iTypeId in ({ids:array})',
                'bind'=>['ids'=>$ids]
            ]);
        }else{
            $types=XHImsProdType::find([
                'conditions'=>'bDelete=0 AND iTypeId in ({ids:array}) AND iCreateUserId =:iCreateUserId:',
                'bind'=>['ids' => $ids,'iCreateUserId' => Main::getLoginUserInfo('userId')]
            ]);
        }

        foreach ($types as $type){
            $type->bDelete = 1;
            if(!$type->save()) {
                return  $this->sendErrorResponse(500,'类型删除失败');
            }
        }
        if(Cache::exists('prodTypeEnum')){
            Cache::delete('prodTypeEnum');
        }
        
        return $this->sendSuccessResponse('类型删除成功，已过滤无法删除的记录');
        
    }

    /**
     * 保存商品
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/9/12
     */
    public function saveProductAction(){
        $id=$this->request->getPost('iProdId','string') ;
        if($id){
            UserPower::checkUserPower('Ims_ProdList_Edit') or die('缺少权限');
            $obj = XHImsProduct::findFirst([
                'conditions'=>'bDelete=0 AND iProdId=:iProdId:',
                'bind'=>['iProdId'=>$id]
            ]);
        }else{
            UserPower::checkUserPower('Ims_ProdList_Add') or die('缺少权限');
            $obj = new XHImsProduct();
        }
        $obj->assign($this->request->getPost());
        $obj->iDefNum=($this->request->getPost('iDefNum')==''?null:$this->request->getPost('iDefNum'));
        $check=$this->checkTypeName($this->request->getPost('sProdName','string'),$id);
        if($check){
            return $this->sendErrorResponse(500,'该商品已存在,请不要重复创建');
        }
        if($obj->save()){
            if(Cache::exists('prodEnum')){
                Cache::delete('prodEnum');
            }
            if($id){
                return $this->sendSuccessResponse('编辑商品成功');
            }else{
                return $this->sendSuccessResponse('新增商品成功');
            }
        }else{
            if($id){
                return $this->sendSuccessResponse(500,'编辑商品失败');
            }else{
                return $this->sendErrorResponse(500,'新增商品失败');
            }
        }
    }

    /**
     * 检查商品名称是否重复
     * @param $name
     * @param null $id
     * @return bool
     * created by dale 2017/9/12
     */
    public function checkProdName($name,$id=null){
        if($id){
            $prod=XHImsProduct::findFirst([
                'conditions'=>'bDelete=0 AND sProdName=:sProdName: AND iProdId!=:iProdId:',
                'bind'=>['sProdName'=>$name,'iProdId'=>$id]
            ]);
        }else{
            $prod=XHImsProduct::findFirst([
                'conditions'=>'bDelete=0 AND sProdName=:sProdName:',
                'bind'=>['sProdName'=>$name]
            ]);
        }
        if($prod){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 删除商品
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/9/12
     */
    public function delProdAction(){
        UserPower::checkUserPower('Ims_ProdList_Del') or die('缺少权限');
        $ids  = $this->request->getPost('ids','string') or die('缺少参数');
        $ids  = explode(',',$ids);
        if(Main::getLoginUserInfo('logonName')!='admin'){
            $prods = XHImsProduct::find([
                'conditions'  => 'bDelete=0 AND iProdId in ({ids:array}) AND iCreateUserId = :iCreateUserId:',
                'bind'        => ['ids' => $ids,'iCreateUserId' => Main::getLoginUserInfo('userId')]
            ]);
        }else{
            $prods=XHImsProduct::find([
                'conditions' => 'bDelete=0 AND iProdId in ({ids:array})',
                'bind'       => ['ids' => $ids],
            ]);
        }
        foreach ($prods as $prod){
            $prod->bDelete = 1; 
            if(!$prod->save()){
                return $this->sendErrorResponse(500,'商品删除失败');
            }
        }
        if(Cache::exists('prodEnum')){
            Cache::delete('prodEnum');
        }
        return $this->sendSuccessResponse('商品删除成功,已过滤无法删除的记录');
    }

    /**
     * 类型表格
     *
     * created by dale 2017/9/12
     */
    public function typeFormAction(){
        $id=$this->request->getQuery('id','string');
        $this->view->pick('product/typeForm');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/product/typeForm.js');
        if($id!=null){

            $type = XHImsProdType::findFirst([
                'conditions'=>'bDelete = 0 AND iTypeId = :iTypeId: ',
                'bind'=>['iTypeId'=>$id],
            ]);

            if(Main::getLoginUserInfo('logonName') != 'admin'){
                if(UserPower::checkUserPower('Ims_ProdList_Edit')
                    && $type->iCreateUserId == Main::getLoginUserInfo('userId')){
                    $check = "";
                }else{
                    $check = "parent.$('#bt_modal_confirm').hide();";
                }
            }else {
                $check = '';
            }
            $typeInfo = json_encode($type->toArray());
        }else{
            $typeInfo='1';
            $check='';
        }


        $this->view->setVars([
            'typeInfo'=> $typeInfo,
            'check'   => $check,
        ]);

    }


    /**
     * 商品表格
     * created by dale 2017/9/12
     */
    public function prodFormAction(){
        $id=$this->request->getQuery('id','string');
        $this->view->pick('product/prodForm');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/product/prodForm.js');
        $types=XHImsProdType::find([
            'columns'=>'iTypeId,sTypeName',
            'conditions'=>'bDelete=0',
        ]);
        $enum=array_column($types->toArray(),'sTypeName','iTypeId');
        if($id!=null){
            $prod=XHImsProduct::findFirst([
                'conditions'=>'bDelete=0 AND iProdId=:iProdId:',
                'bind'=>['iProdId'=>$id],
            ]);
            if(Main::getLoginUserInfo('logonName') != 'admin'){
                if(UserPower::checkUserPower('Ims_ProdList_Edit')
                    && $prod->iCreateUserId == Main::getLoginUserInfo('userId')){
                    $check = "";
                }else{
                    $check = "parent.$('#bt_modal_confirm').hide();";
                }
            }else {
                $check = '';
            }
            $prodInfo=json_encode($prod->toArray());
        }else{
            $prodInfo='1';
            $check='';
        }
        $this->view->setVars([
            'prodInfo'=> $prodInfo,
            'types'=>$enum,
            'check'=>$check,
        ]);
    }



}